package org.example.system.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.example.system.entity.Post;
import org.example.system.entity.User;
import org.example.system.service.PostService;
import org.example.system.service.UserService;
import org.example.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * 帖子控制层
 */
@RestController
@Slf4j
@RequestMapping("/app/post")
public class PostController {

    @Autowired
    private PostService postService;
    @Autowired
    private UserService userService;

    @PostMapping("/upload")
    public R upload(@RequestParam("userId") String userId,@RequestParam("postCount") String postCount, @RequestParam("file") @RequestBody MultipartFile file) throws FileNotFoundException {

        if (file.isEmpty()) {
            return R.fail("上传文件为空");
        }
        String fold = "/home/deploy/team-proj/app-api/config/static/image/posts/" + userId + "/" + postCount + "/";
        System.out.println(fold);
        int fileCount = 0;
        File folder = new File(fold);
        if  (!folder.exists()  && !folder.isDirectory()){folder.mkdirs();} //如果目录不存在，创建目录
        File[] files = folder.listFiles();
        if (files != null){fileCount = files.length;}   //获取文件夹下数量
        String newFileName = fileCount + ".png";
        // 创建一个文件对象，表示要保存的文件
        File dest = new File(fold + newFileName);
        try {
            // 将上传的文件内容写入到目标文件中
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            return R.fail("上传失败");
        }
        return R.ok(true);
    }

    /**
     * 按分页查询联查用户表
     * @param post
     * @return
     */
    @GetMapping("/list")
    public R list(Post post){
        IPage<Post> page = postService.select(post);
        log.info("------------ PostController | list | selectPage | return : {} ", JSON.toJSONString(page));
        return R.ok(page);
    }

    /**
     * 添加帖子
     * @param post
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody Post post){
        log.info("--------- PostController | add | input : {}", JSON.toJSON(post));
        int row = postService.add(post);
        if(row <= 0){
            return  R.fail("添加失败");
        }
        User user = userService.getOne(post.getUserId());
        user.setId(post.getUserId());
        user.setSend(user.getSend() + 1);
        userService.update(user);
        return R.ok("添加成功");
    }

    /**
     * 修改
     * @param post
     * @return
     */
    @PutMapping("/update")
    public R update(@RequestBody Post post){
        log.info("--------- PostController | update | input : {}", JSON.toJSON(post));
        if(null == post.getId() || post.getId() <= 0){
            return R.fail("参数错误:ID未传入");
        }
        int row = postService.update(post);
        if(row <= 0){
            return  R.fail("修改失败");
        }
        return R.ok("修改成功");
    }

    /**
     * 根据id查询帖子数据
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getInfo(@PathVariable("id") Long id){
        log.info("--------- PostController | getInfo | input : {}", JSON.toJSON(id));
        return R.ok(postService.getOne(id));
    }

    /**
     * 根据用户ID查询已经发布的帖子数量
      * @param userId
     * @return
     */
    @GetMapping("/selectPostCount")
    public R getPostCount(Long userId){

        return R.ok(postService.getPostCount(userId));
    }

}
